#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
更新数据库中的图片URL
将网络图片URL替换为本地图片路径
"""

import os
import sys
import django
import random

# 添加项目路径
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'backend'))

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HuaXianGuan.settings')
django.setup()

from apps.flowers.models import Flower, FlowerCategory, FlowerImage

def update_flower_images():
    """更新鲜花商品的图片"""
    
    # 本地图片路径
    local_images = [
        '/images/flowers/roses_1.jpg',
        '/images/flowers/roses_2.jpg', 
        '/images/flowers/roses_3.jpg',
        '/images/flowers/tulips_2.jpg',
        '/images/flowers/sunflowers_2.jpg'
    ]
    
    # 获取所有鲜花商品
    flowers = Flower.objects.all()
    
    print(f"开始更新 {flowers.count()} 个鲜花商品的图片...")
    
    for flower in flowers:
        # 随机选择一张本地图片
        random_image = random.choice(local_images)
        
        # 更新主图
        flower.main_image = random_image
        
        # 更新详情图片（JSON格式）
        flower.detail_images = [random_image]
        
        flower.save()
        
        print(f"已更新商品: {flower.name} -> {random_image}")
    
    print("鲜花商品图片更新完成！")

def update_category_images():
    """更新分类的图片"""
    
    # 分类图片映射
    category_images = {
        '玫瑰': '/images/flowers/roses_1.jpg',
        '郁金香': '/images/flowers/tulips_2.jpg', 
        '向日葵': '/images/flowers/sunflowers_2.jpg'
    }
    
    categories = Category.objects.all()
    
    print(f"开始更新 {categories.count()} 个分类的图片...")
    
    for category in categories:
        # 根据分类名称选择对应图片
        if category.name in category_images:
            category.image = category_images[category.name]
        else:
            # 默认使用玫瑰图片
            category.image = '/images/flowers/roses_1.jpg'
        
        category.save()
        
        print(f"已更新分类: {category.name} -> {category.image}")
    
    print("分类图片更新完成！")

def main():
    """主函数"""
    print("=== 数据库图片更新工具 ===")
    
    try:
        # 更新鲜花商品图片
        update_flower_images()
        
        # 更新分类图片
        update_category_images()
        
        print("\n✅ 所有图片更新完成！")
        
    except Exception as e:
        print(f"❌ 更新失败: {e}")

if __name__ == "__main__":
    main()